"""
作者：Huayu Zong
日期：2023年04月日
"""
import logging

# log = logging.getLogger("【test】")
# log.setLevel(logging.DEBUG)
# log.debug("123")
# log.info("456")
# log.warning("789")
# log.error("zhy")

# 设置打印日志的级别，level级别以上的日志会打印出
# level=logging.DEBUG 、INFO 、WARNING、ERROR、CRITICAL
# def log_testing():
#     log = logging.getLogger("test")
#     log.setLevel(logging.DEBUG)
#     # 此处进行Logging.basicConfig() 设置，后面设置无效
#     #logging.basicConfig(level=logging.DEBUG)
#     log.debug('debug，用来打印一些调试信息，级别最低')
#     log.info('info，用来打印一些正常的操作信息')
#     log.warning('waring，用来用来打印警告信息')
#     log.error('error，一般用来打印一些错误信息')
#     log.critical('critical，用来打印一些致命的错误信息，等级最高')
#
# log_testing()

# def log_testing():
#     selflogger = logging.getLogger('THIS-LOGGING')
#     selflogger.setLevel(logging.DEBUG)
#     selflogger.debug('debug，用来打印一些调试信息，级别最低')
#     selflogger.info('info，用来打印一些正常的操作信息')
#     selflogger.warning('waring，用来用来打印警告信息')
#     selflogger.error('error，一般用来打印一些错误信息')
#     selflogger.critical('critical，用来打印一些致命的错误信息，等级最高')
#
# log_testing()


def console_out(logFilename):
    ''' Output log to file and console '''
    # Define a Handler and set a format which output to file
    logging.basicConfig(
        level=logging.DEBUG,  # 定义输出到文件的log级别，
        format='%(asctime)s  %(filename)s : %(levelname)s  %(message)s',  # 定义输出log的格式
        datefmt='%Y-%m-%d %A %H:%M:%S',  # 时间
        filename=logFilename,  # log文件名
        filemode='w')  # 写入模式“w”或“a”
    # Define a Handler and set a format which output to console
    console = logging.StreamHandler()  # 定义console handler
    console.setLevel(logging.INFO)  # 定义该handler级别
    formatter = logging.Formatter('%(asctime)s  %(filename)s : %(levelname)s  %(message)s')  # 定义该handler格式
    console.setFormatter(formatter)
    # Create an instance
    #logging.getLogger().addHandler(console)  # 实例化添加handler

    # Print information              # 输出日志级别
    logging.debug('logger debug message')
    logging.info('logger info message')
    logging.warning('logger warning message')
    logging.error('logger error message')
    logging.critical('logger critical message')


if __name__ == "__main__":
    print(0x1522)
    bytearray_data = bytearray("zhy")


    # 绑定回调函数
    def __bind_callback_function(self):

        if self.__callback_dict is not None:
            self.connectAliyun_btn.bind("<Button-1>", self.__callback_dict['connect_aliyun'])


    # 更新上位机连接阿里云状态
    def Update_Aliyun_ConnectState(self, val):
        if val:
            self.Aliyun_is_Connected_Label["bg"] = "green"
        else:
            self.Aliyun_is_Connected_Label["bg"] = "red"
            self.OTA_CAN_is_Connected_Wifi_Label["bg"] = "red"
        pass


    # 更新OTA-CAN工具连接WIFI状态
    def Update_OTA_CAN_ConnectState(self, val):
        if val:
            self.OTA_CAN_is_Connected_Wifi_Label["bg"] = "green"
        else:
            self.OTA_CAN_is_Connected_Wifi_Label["bg"] = "red"
        pass


    ####################################  以下是回调函数   #######################################









    def update_ui(self):
        while not self.__msg_queue.empty():
            content = self.__msg_queue.get()

            if isinstance(content, dict):
                # 更新client阿里云连接状态
                val = get_data_from_dict(content, 'client_connect_aliyun_status')
                if val is not None:
                    self.Update_Aliyun_ConnectState(val)
                    continue

                # 更新OTA-CAN连接阿里云状态
                val = get_data_from_dict(content, 'OTA_CAN_ConnectAliyunState')
                if val is not None:
                    self.Update_OTA_CAN_ConnectState(val)
                    continue

                # 单块程序更新成功
                val = get_data_from_dict(content, 'single_block_update_success')
                if val is not None:
                    if val is True:
                        # 更新进度条
                        index = self.send_prm_block_index
                        self.__update_percent += len(self.fixed_size_program_list[index]) * 100 / self.file_total_size
                        self.set_progressBar_value(round(self.__update_percent, 0))

                        # 更新成功，弹出对话框
                        if self.__update_percent == 100:
                            a = messagebox.showinfo("询问：", "真要退出吗？")  # 按下确定，返回'ok'
                            if a == 'ok':
                                self.set_progressBar_value(0)  # 清空进度条
                                self.clear_variable_value()  # 清空文件操作

                        # 发送的index加1
                        self.send_prm_block_index += 1

                        if self.send_prm_block_index == self.program_block_count:  # 发送结束
                            self.send_prm_block_index = 0
                        else:  # 继续发送
                            self.get_single_program_block_info(self.send_prm_block_index)
                            self.__send_queue.put(self.single_block_prm_info_dict)

                # 程序更新完毕
                val = get_data_from_dict(content, 'program_update_complete')
                if val is not None:
                    if val is True:
                        # 清空fixed_size_program_list
                        self.fixed_size_program_list.clear()
                        self.clear_variable_value()

                        # self.__msg_queue.put("程序更新成功，请重启目标控制器！\n")

            # 更新文本框
            self.append_text_box(content)
        # 周期更新
        self.main_window.after(UpdateTextBoxPeriod, self.update_ui)




    ####################################   回调函数结束    #######################################

    pass